<template>
  <!-- 弹窗 -->
  <el-dialog v-model="dialogVisible" fullscreen="true" v-if="dialogVisible" align-center :show-close="false"
    :title="title" :close-on-click-modal="false" width="80%">
    <el-card>
      <el-form ref="ruleFormRef" style="max-width: 800px" :model="ruleForm" status-icon :rules="rules"
        label-width="auto" class="demo-ruleForm">
        <el-form-item label="药品组合名称" prop="name">
          <el-input v-model="ruleForm.name" />
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-select clearable v-model="value" placeholder="请选择分类" style="width: 120px">
            <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="价格/元" prop="price">
          <el-input v-model="ruleForm.price" />
        </el-form-item>
        <el-form-item label="药品组合菜品" prop="">
          <el-button @click="visible = true">添加菜品</el-button>
          <el-table :data="tableData" style="width: 100%" v-if="tableData.length > 0">
            <el-table-column fixed prop="name" label="名称" width="100" align="center" />
            <el-table-column prop="price" label="原价" width="100" align="center" />
            <el-table-column prop="copies" label="份数" width="200" align="center">
              <template v-slot="{ row }">
                <el-input-number v-model="row.copies" :min="1" />
              </template>

            </el-table-column>
            <el-table-column fixed="right" label="操作" width="180" align="center">
              <template v-slot="{ row }">
                <el-button link type="primary" size="small" @click="deleteRow(row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-dialog v-model="visible" width="60%" title="添加菜品" append-to-body>
            <el-card class="centered-card">
              <Transfer v-if="visible" ref="transfer" :ids="ids"></Transfer>
              <el-row>
                <el-button style="margin-left: 40%;" @click="addToTable()">完成</el-button>
                <el-button @click="visibleCancel">取消</el-button>
              </el-row>

            </el-card>
          </el-dialog>

        </el-form-item>
        <el-form-item label="图片" prop="image">
          <Upload ref="upload" :oldImage="oldImage"></Upload>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="ruleForm.description" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="ruleForm.status">
            <el-radio :label="1">起售</el-radio>
            <el-radio :label="0">禁售</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item style="margin-left: 100px;">
          <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
          <el-button type="primary" @click="cancel()">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </el-dialog>
</template>

<script lang="ts" setup>
import Upload from '../../components/Upload.vue'
import { reactive, ref, defineProps } from 'vue'
//分类选择框
const categoryList = ref([])
const value = ref()


// 获取分类列表
import { getCategories } from '@/apis/category.js'
async function getCategoryList() {
  const res = await getCategories(2)
  console.log(res.data.data)
  categoryList.value = res.data.data
}
getCategoryList()


const props = defineProps({
  onSubmit: Function
})
const tableData = ref([])
//表格
//删除
const deleteRow = (index: number) => {
  //表格数据删除
  tableData.value.splice(index, 1)
  console.log(index)
  //ids(已选数组)数据删除
  let filtered = [];
  for (let key in ids.value) {
    if (ids.value[key] !== index.dishId) {
      filtered[key] = ids.value[key];
    }
  }
  ids.value = filtered;
}
//穿梭框
import Transfer from './Transfer.vue'
const visible = ref(false)
const transfer = ref(null)
import type { FormInstance, FormRules } from 'element-plus'

const ids = ref([])
import { getDishByIds } from '@/apis/dish.js'
//添加到表格
async function addToTable() {
  // 把选中的添加到ids ,并过滤掉ids中已经有的
  transfer.value.value.forEach((item: any) => {
    if (!ids.value.includes(item)) {
      ids.value.push(item)
    }
  })
  if (ids.value.length === 0) {
    visible.value = false;
    return
  }
  console.log(ids)
  //将ids数组拼成逗号分隔的字符串
  const idArray = Object.values(ids.value);
  const idsStr = idArray.join(',');
  const res = await getDishByIds(idsStr)
  tableData.value = tableData.value.concat(res.data.data.filter(item2 =>
    !tableData.value.some(item1 => item1.dishId === item2.dishId)));
  console.log(tableData.value)
  visible.value = false;
}



const upload = ref()
const dialogVisible = ref(false)
const isadd = ref()
const title = ref('')
function changeDialogVisible(val: boolean) {
  if (val === true) {
    title.value = "新增药品组合"
  }
  if (val === false) {
    title.value = "修改药品组合"
  }
  dialogVisible.value = true
  isadd.value = val;
}
const oldImage = ref('')
import { nextTick } from 'vue';
import { getSetmealDishes } from '@/apis/setmeal.js';
async function editFormData(row: any) {
  //获取图片
  oldImage.value = row.image
  //获取表格数据
  const res = await getSetmealDishes(row.id)
  tableData.value = res.data.data
  //给ids添加值
  tableData.value.forEach((item: any) => {
    ids.value.push(item.dishId)
  })
  console.log(ids)
  nextTick(() => {
    ruleForm.id = row.id
    ruleForm.name = row.name
    value.value = row.categoryId
    ruleForm.price = row.price
    ruleForm.image = row.image
    ruleForm.description = row.description
    ruleForm.status = row.status
  })

}
defineExpose({
  changeDialogVisible,
  editFormData
})
//表单
const ruleFormRef = ref<FormInstance>()

const ruleForm = reactive({
  id: null,
  name: '',
  categoryId: null,
  price: null,
  image: '',
  description: '',
  status: null,
  setmealDishList: []
})

const checkPrice = (rule: any, value: any, callback: any) => {
  if (value === null || value === '') {
    callback(new Error('请输入价格!'))
  } else if (!/^\d+(\.\d{1,2})?$/.test(value)) {
    callback(new Error("菜品价格格式有误，请输入大于零且最多保留两位小数的金额!"))
  } else {
    callback()
  }
}

const rules = reactive<FormRules<typeof ruleForm>>({
  name: [{ required: true, message: '请输入药品组合名称', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择分类!', trigger: 'blur' }],
  price: [{ validator: checkPrice, trigger: 'blur' },],
  image: [{ required: true, message: '请添加图片!', trigger: 'blur' }],
  status: [{ required: true, message: '请设置状态!', trigger: 'blur' }],
})
import { addSetmeal } from '@/apis/Setmeal.js'
import { ElMessage } from 'element-plus'

import { updateSetmeal } from '@/apis/Setmeal.js'
const submitForm = (formEl: FormInstance | undefined) => {
  ruleForm.image = upload.value.imageUrl
  ruleForm.categoryId = value.value
  console.log(upload.value.imageUrl);
  console.log(tableData.value);
  if (!formEl) return
  formEl.validate(async (valid) => {
    ruleForm.setmealDishList = tableData.value
    if (valid) {
      if (isadd.value === true) {
        //提交添加请求
        const res = await addSetmeal(ruleForm)
        console.log(res.data.code);
        if (res.data.code === 0) {
          ElMessage.error(res.data.msg)
          return
        }
        resetForm(formEl)
        ElMessage.success("添加成功")
        dialogVisible.value = false

        //让图片清空
        oldImage.value = ''
        //清空tableData
        tableData.value = []
        ///清空ids
        ids.value = []
        //清空value
        value.value=null;
        //刷新表格
        props.onSubmit()
        console.log('提交成功!')
      } else {
        //提交 修改请求
        const res = await updateSetmeal(ruleForm)
        console.log(res.data.code);
        if (res.data.code === 0) {
          ElMessage.error(res.data.msg)
          return
        }
        resetForm(formEl)
        ElMessage.success("修改成功")
        dialogVisible.value = false
        //清空tableData
        tableData.value = []
        //清空ids
        ids.value = []
        //清空value
        value.value=null;
        //让图片清空
        oldImage.value = ''
        //刷新表格
        props.onSubmit();
      }
    } else {
      console.log('error submit!')
      return false
    }
  })
}
function cancel() {
  //清空图片
  oldImage.value = ''
  //清空tableData
  tableData.value = []
  //清空ids
  ids.value = []
  //清空分类选择
  value.value=[]
  resetForm(ruleFormRef.value)
  dialogVisible.value = false
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
function  visibleCancel(){
  visible.value = false
  value.value=[];
}
</script>

<style>
.centered-card {
  text-align: center;
}
</style>